package com.sddfp.system.controller;

//import com.sddfp.client.pojo.TestBankApi;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import com.sddfp.client.access.TradeLogApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试负载均衡：
 * 1、客户端项目远程调用；
 * 2、启动多个服务端
 * 3、客户端查看调用的是哪个服务端
 */
@RestController
@RequestMapping("/test")
public class TestController {

    // 注入feign客户端接口代理对象
    @Autowired
    private TradeLogApi testBankApi;

    /**
     * 测试
     * 启动时候报错：
     * 1、Consider renaming one of the beans or enabling overriding by setting
     * spring.main.allow-bean-definition-overriding=true
     * 2、解决： 在yml中配置允许bean的重写
     */
    @GetMapping
    public String loadbalance(){

        String s = testBankApi.showPort();
        System.out.println("s = " + s);

        return s;
    }

//    @GetMapping("/find/{id}")
//    @HystrixCommand(fallbackMethod = "errorFallback")
//    public Result find(@PathVariable("id")Integer id){
//        if (id < 10) {
//            throw new BusinessException();
//        }
//        return Result.ok("查找成功");
//    }
//
//    // 降级方法
//    public Result errorFallback(@PathVariable("id")Integer id){
//        return Result.fail("降级方法");
//    }

    @GetMapping("find/{id}")
    @HystrixCommand(fallbackMethod = "errorFallback",commandProperties = {
            // 是否开启断路器
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED,value = "true"),
            // 请求错误率大于 50% 就启动熔断器
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE,value = "50"),
            // 默认10秒内访问接口达到20次，且错误率大于50%则打开断路器，触发熔断； 为了方便测试，这里修改请求数为10
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,value = "10"),
            //断路多久以后开始尝试是否恢复，默认5s
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS,value = "10000")
    })
    public String findMemberById(@PathVariable("id")Integer id) {
        if (id<0) {
            throw new RuntimeException("id不能为负数");
        }
        return Thread.currentThread().getName() + " 调用成功";
    }

    // 默认降级方法，返回string
    public String errorFallback(@PathVariable("id")Integer id){
        return "默认降级方法";
    }

}
